class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def findLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        out = [[]]

        def search(node):
            if not node.left and not node.right:
                out[0].append(node.val)
                return 0
            max_value = 0
            if node.left:
                max_value = max(search(node.left), max_value)
            if node.right:
                max_value = max(search(node.right), max_value)
            now_value = max_value + 1
            if now_value == len(out):
                out.append([node.val])
            else:
                out[now_value].append(node.val)
            return now_value
        search(root)
        return out
